<template>
	<u-popup :show="visiable" closeable @close="hiddenCanvas">
		<view class="share-model" @touchstart="" @touchmove="" @touchend="">
			<template v-if="visiable">
				<view class="mask"></view>
				<view class="content" :style="{width:`${designWidth}rpx;`, height: `${designHeight}rpx;`}">
					<canvas canvas-id="posterid" class="canvas"
						:style="{width:`${canvasWidth}rpx;`, height:`${canvasHeight}rpx;`}" disable-scroll="true"
						@touchstart="" @touchmove="" @touchend=""></canvas>
					<button class="share" @click="savePoster"
						:style="{ 'margin-top':`${gap}rpx;`,height:`${shareBtnHeight}rpx;`}">保存图片并分享到朋友圈</button>
					<image src="@/static/icon/ic_close.png" class="close-img" @click="hiddenCanvas"></image>
				</view>
			</template>
		</view>
	</u-popup> 
</template> 

<script>
	import {
		mapState
	} from 'vuex'
	export default {
		name:'xPoster',
		props: {
			name: String,
			imageUrl: String,
			qrcode: String,
		},
		data() {
			return {
				visiable: false,
				screenHeight: 0, //rpx
				screenWidth: 0, //rpx

				designWidth: 690, //rpx为单位，左右空出各30rpx,内部再左右15px， 最大可允许的设计宽度
				aspectRatio: 16 / 9, //弹窗的高、宽比例， 一旦超出屏幕， 再按比例调整，保证设计的designWidth, designHeight在一屏上可以显示全
				designHeight: 0, //rpx为单位，

				canvasWidth: 0, //rpx
				canvasHeight: 0, // rpx为单位
				shareBtnHeight: 80, // rpx为单位
				closeBtnHeight: 80, // rpx为单位
				gap: 40, //各元素间间距 rpx为单位

				imageWidth: 0, //rpx
				imageHeight: 0,

				unit: 1, //单位像素对应的rpx
			}
		},
		computed: {
			...mapState(['device'])

		},
		mounted() {
			let screenHeightPx = this.device.screenHeight
			let screenWidthPx = this.device.screenWidth

			this.unit = 750 / screenWidthPx; //单位像素对应的rpx
			this.screenHeight = screenHeightPx * this.unit //对应的rpx
			this.screenWidth = screenWidthPx * this.unit //对应的rpx
			this.designHeight = this.designWidth * this.aspectRatio
			console.log("this.designMaxHeight =", this.designHeight)
			// let verticalMinOffset = {
			// 	up: 20,
			// 	bottom: 200 //底部保存按钮+关闭按钮空间
			// } //上下最小偏移量各为20rpx
			if (this.designHeight > this.screenHeight) {
				this.designHeight = this.screenHeight 
			}
			this.designWidth = this.designHeight / this.aspectRatio

			this.canvasHeight = this.designHeight - (this.gap+this.shareBtnHeight+this.gap+this.closeBtnHeight)
			this.canvasWidth = this.designWidth
		},
		created() {

		},
		methods: {
			//显示
			showCanvas() {
				this.visiable = true
				this.setStopter();
			},
			// 点击关闭
			hiddenCanvas() {
				this.visiable = false
				this.$emit("closeShare")
			},

			getImageInfo(url) {
				return new Promise((resolve, reject) => {
					uni.getImageInfo({
						src: url,
						success: function(res) {
							resolve(res);
						},
						fail: function(err) {
							reject(err);
						}
					});
				});
			},


			// 绘制海报
			async setStopter() {
				uni.showLoading({
					title: '加载中...',
					mask: false
				})
				var _this = this
				console.log("_this.imageUrl=", _this.imageUrl)
				try {
					const imageInfo = await _this.getImageInfo(_this.imageUrl);
					// 在这里可以进行对图片宽高的处理操作
					_this.imageWidth = imageInfo.width * _this.unit
					_this.imageHeight = imageInfo.height * _this.unit
				} catch (error) {
					console.error('获取图片信息失败：', error);
					uni.hideLoading()
					return;
				}

				var ctx = uni.createCanvasContext('posterid', _this) //创建画笔
				// 设置背景颜色
				// 绘制一个填充整个Canvas的矩形
				_this.drawRoundRect(ctx, 0, 0, _this.canvasWidth / _this.unit, _this.canvasHeight / _this.unit, 10,
					'coral')
				// console.log("_this.canvasWidth =", _this.canvasWidth, ",canvasHeight=", _this.canvasHeight)
				
				// 绘制绘图空间
				let gap= 20 //以rpx为单位. 上面图片与底部小程序码的间距,以及顶部空出的空间，上下左右各gap rpx空间
				let startDrawXPX = 30 //以px为单位
				let startDrawYPX = 20 //以px为单位
				let drawWidth =  _this.canvasWidth-(2*startDrawXPX*_this.unit) //以rpx为单位，左右各startDrawXPX px
				let drawHeight = _this.canvasHeight-(2*startDrawYPX*_this.unit) //以rpx为单位, 上下各 startDrawYPX px
				console.log("canvasWidth=", _this.canvasWidth / _this.unit, ",canvasHeight=", _this.canvasHeight / _this.unit, ", drawWidth=", drawWidth , ",drawHeight=", drawHeight)
				_this.drawRoundRect(ctx, startDrawXPX, startDrawYPX, drawWidth / _this.unit, drawHeight / _this.unit, 0, 'white')
				
				//在绘图空间的最大可允许高度进行等比缩放
				let startDrawContentXPX = 10 //以px为单位
				let startDrawContentYPX = 10 //以px为单位
				let {
					dx,
					dy,
					dw,
					dh
				} = _this.aspectFit(_this.imageWidth, _this.imageHeight, drawWidth-2*startDrawContentXPX*this.unit, 2/3*drawHeight - 2*startDrawContentYPX*this.unit )
				console.log("this.imageUrl dx, dy, dw, dh=", startDrawXPX+startDrawContentXPX+dx, startDrawYPX+startDrawContentYPX+dy, dw, dh)
				let image = await _this.downloadImage(_this.imageUrl)
				if (image.tempFilePath) {
					ctx.save()
					ctx.drawImage(image.tempFilePath, startDrawXPX+startDrawContentXPX+dx, startDrawYPX+startDrawContentYPX+dy, dw, dh); //绘制完成后，会放置再中间，所以我们这里指定的点还是0，0开始
					ctx.restore()
				}

				let bottomTextHeight = 40 //底部文字高度， rpx
				let qrcodeMaxHeight = 1/3*drawHeight - 2*gap - bottomTextHeight-gap //2*gap:小程序码与底部文字，底部文字与绘画窗口间距
				let {
					dx: dx2,
					dy: dy2,
					dw: dw2,
					dh: dh2
				} = _this.aspectFit(430, 430, drawWidth-2*startDrawContentXPX*this.unit, qrcodeMaxHeight)
				console.log("this.qrcode dx2, dy2, dw2, dh2=", dx2, dy2, dw2, dh2)
				let qrcodeStartY = startDrawYPX+2/3*drawHeight/_this.unit+gap/this.unit+dy2
				ctx.drawImage(_this.qrcode, startDrawXPX+startDrawContentXPX+dx2, qrcodeStartY, dw2, dh2);

				let bottomTextStartY = (qrcodeStartY+dh2+this.gap/this.unit)
				_this.drawText(ctx, 12, 'rgb(160, 160, 160)', '立即识别二维码了解更多', (_this.canvasWidth/2 - 130)/_this.unit, bottomTextStartY)
				// _this.drawText(ctx, 12, 'rgb(160, 160, 160)', '立即识别二维码了解更多', (_this.canvasWidth/2 - 130)/_this.unit, (_this.canvasHeight - 40)/_this.unit)
				 
				ctx.draw(true, () => {
					uni.hideLoading()
				})
				console.log('绘画完成')
			},
			drawText(ctx, fs, color, txt, x, y) { //绘制文字
				ctx.setFontSize(fs)
				ctx.setFillStyle(color)
				ctx.fillText(txt, x, y)
			},
			//圆角矩形
			drawRoundRect(ctx, x, y, width, height, radius, color) {
				ctx.save();
				ctx.beginPath();
				ctx.setFillStyle(color);
				ctx.setStrokeStyle(color)
				ctx.setLineJoin('round'); //交点设置成圆角
				ctx.setLineWidth(radius);
				ctx.strokeRect(x + radius / 2, y + radius / 2, width - radius, height - radius);
				ctx.fillRect(x + radius, y + radius, width - radius * 2 + 1, height - radius * 2 + 1);
				ctx.stroke();
				ctx.closePath();
			},
			downloadImage(url) { //绘制网络图片，网络图片需要先缓存到本地再绘制
				return new Promise((resolve, reject) => {
					uni.downloadFile({ // 还可以使用 uni.getImageInfo 方法
						url: url,
						success: (res) => {
							return resolve(res)
						},
						fail: (err) => {
							return reject(err)
						}
					})
				})
			},

			// 保存海报
			saveImageToPhotosPoster() {
				uni.showLoading({
					title: '海报下载中...'
				});
				uni.canvasToTempFilePath({
					canvasId: 'posterid',
					success: function(res) {
						uni.saveImageToPhotosAlbum({
							filePath: res.tempFilePath,
							success(result) {
								uni.hideLoading()
								uni.showToast({
									title: '海报已存入相册',
									icon: 'success',
									duration: 2000
								})
							},
							fail: () => {
								uni.hideLoading()
							}
						})
					},
					complete(res) { //不管成功或者失败都会执行
						console.log('canvas转成图片结果', res)
					}
				}, this);
			},

			aspectFit(imageWidth, imageHeight, drawWidth, drawHeight) {
				let scale = Math.min(drawWidth / imageWidth, drawHeight / imageHeight)

				// 计算缩放后的宽度和高度
				let dw = imageWidth * scale;
				let dh = imageHeight * scale;

				// 计算水平和垂直偏移量使图片居中显示
				let dx = (drawWidth - dw) / 2;
				let dy = (drawHeight - dh) / 2;

				return {
					dx: dx / (this.unit),
					dy: dy / (this.unit),
					dw: dw / (this.unit),
					dh: dh / (this.unit)
				}

			},


			//保存图片到相册
			savePoster() {
				const that = this;
				// #ifdef MP-WEIXIN
				uni.getSetting({
					success: res => {
						if (res.authSetting['scope.writePhotosAlbum']) {
							that.saveImageToPhotosPoster()
						} else {
							uni.authorize({
								scope: 'scope.writePhotosAlbum',
								success: () => {
									that.saveImageToPhotosPoster()
								},
								fail: () => {
									uni.showModal({
										title: '提示',
										content: '请先在设置页面打开“保存相册”使用权限',
										confirmText: '去设置',
										cancelText: '算了',
										success: data => {
											if (data.confirm) {
												uni.openSetting();
											}
										}
									});
								},
								complete: res => {}
							});
						}
					}
				});
				// #endif
			}
		}
	}
</script>

<style lang="scss" scoped>
	.share-model {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		display: flex;
		align-items: center;
		justify-content: center;
		z-index: 1;

		.mask {
			position: absolute;
			left: 0rpx;
			top: 0rpx;
			width: 100%;
			height: 100%;
			background-color: #000;
			opacity: 0.5;
		}

		.content {
			display: flex;
			flex-direction: column;
			align-items: center;
			border-radius: 20rpx;
			position: relative;
			z-index: 1;
			
			.canvas {
				display: flex;
				flex-direction: column;
				align-items: center;
			}

			.share {
				// position: absolute;
				// bottom: 0rpx;
				margin-top: 20rpx;
				width: 100%;
				border-radius: 40rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				color: white;
				background-color: orange;
			}
			
			
			.close-img {
				// position: absolute;
				// bottom: 0px;
				// top: -40rpx;
				// right: -40rpx;
				margin-top: 20rpx;
				width: 80rpx;
				height: 80rpx;
				border-radius: 40rpx;
				z-index: 999;
			}
		}
	}
</style>